<template>
  <div class="search-suggestion">
    <van-cell
      @click="$emit('changeValue', item)"
      v-for="(item, index) in suggestionList"
      :key="index"
      icon="search"
      ><div v-html="highlightText(item)"></div
    ></van-cell>
  </div>
</template>
<script>
import { getSearchSuggestion } from '@/api/search'
import { debounce } from 'lodash'
export default {
  props: ['searchValue'],
  name: 'suggestion',
  created() {},
  computed: {},
  watch: {
    searchValue: {
      handler: debounce(function(val) {
        this.getSuggestion(val)
      }, 250),
      immediate: true
    }
  },
  data() {
    return {
      suggestionList: []
    }
  },
  methods: {
    async getSuggestion(data) {
      try {
        const { data: res } = await getSearchSuggestion(data)
        this.suggestionList = res.data.options
      } catch (error) {
        console.log(error)
        this.$toast('获取搜索建议失败')
      }
    },
    highlightText(text) {
      const highlightStr = `<span style="color:red">${this.searchValue}</span>`
      // 正则表达式 // 中间的内容都会当作匹配字符来使用，而不是数据变量
      // 如果需要根据数据变量动态的创建正则表达式，则手动 new RegExp
      // RegExp 正则表达式构造函数
      //    参数1：匹配模式字符串，它会根据这个字符串创建正则对象
      //    参数2：匹配模式，要写到字符串中
      const reg = new RegExp(this.searchValue, 'gi')
      // text.replace(/匹配的内容/gi, highlightStr)
      return text.replace(reg, highlightStr)
    }
  }
}
</script>
<style lang="less" scoped></style>
